package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.common.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.pojo.Member;
import com.atguigu.service.MemberService;
import com.atguigu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/Login")
public class LoginController {
    @Autowired
    JedisPool jedisPool;
    @Reference
    MemberService memberService;
    @RequestMapping("/check")
    public Result check(@RequestBody Map map , HttpServletResponse response){

       String telephone= (String) map.get("telephone");
       String validateCode= (String) map.get("validateCode");
        String codeFromRedis = jedisPool.getResource().get(telephone+RedisMessageConstant.SENDTYPE_LOGIN);

        if(codeFromRedis==null||!codeFromRedis.equals(validateCode)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);

        }

       Member member= memberService.getMemberByTelephone(telephone);
        if (member==null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.save(member);


            Cookie cookie =new Cookie("member_login_telephone",telephone);
            cookie.setMaxAge(60*60*24*30);
            cookie.setPath("/");
            response.addCookie(cookie);

        }
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
